package com.wzt.lianfirecontrol.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mob.pushsdk.MobPush;
import com.mob.pushsdk.MobPushCallback;
import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.recode.AppVersionModel;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.user.CompanyModel;
import com.wzt.lianfirecontrol.bean.recode.user.RoleConstant;
import com.wzt.lianfirecontrol.bean.recode.user.UserInfoModel;
import com.wzt.lianfirecontrol.fragment.BarFloorFragment;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.fragment.WebFragment;
import com.wzt.lianfirecontrol.fragment.home.HomeFragment;
import com.wzt.lianfirecontrol.fragment.home.HomeMessageFragment;
import com.wzt.lianfirecontrol.fragment.home.HomeStatisticFragment;
import com.wzt.lianfirecontrol.fragment.home.UserCenterFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.utils.DialogUtils;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.SimpleCache;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

public class MainActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout ll_main_content;
    // 头部标题
    private View include_head_title;
    private TextView tv_title;
    // 底部按钮
    private LinearLayout ll_home;
    private ImageView iv_home;
    private TextView tv_home;
    private LinearLayout ll_message;
    private ImageView iv_message;
    private TextView tv_message;
    private LinearLayout ll_knowledge;
    private ImageView iv_knowledge;
    private TextView tv_knowledge;
    private LinearLayout ll_my;
    private ImageView iv_my;
    private TextView tv_my;
    // 首页内容
    private BaseFragment[] baseFragments = new BaseFragment[4];
    private int currentSelectPosition = -1;

    private double back_pressed;// 两次返回

    private static final int APP_UPDATE_WHAT = 0;

    private Dialog updateDialog;


    private RelativeLayout rl_weibao_content;
    private View include_weibao_head_title;
    private BaseFragment baseFragment;
    private TextView tv_choose_company;
    private ImageView iv_setting;
    private ImageView iv_add_img;

    private static final int GET_COMPANY_WHAT = 1;// 获取公司树
    private Dialog changeCompanyDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.a_main);
        setImmerseLayout(findViewById(R.id.include_head_title), findViewById(R.id.include_head_title).findViewById(R.id.rl_head_content));
        setImmerseLayout(findViewById(R.id.include_weibao_head_title), findViewById(R.id.include_weibao_head_title).findViewById(R.id.rl_head_content));
        initView();
        //获取注册id
        MobPush.getRegistrationId(new MobPushCallback<String>() {
            @Override
            public void onCallback(String data) {
              //  System.out.println(Thread.currentThread().getId() + " RegistrationId:" + data);
                Log.e("RegistrationId:",data);
            }
        });


        List<String> alias = UserInfoModel.getUserInfo(this).getRoleAlias();
        // 维保人员和维保管理人员只显示预约维保单
       // 组织管理员 ROLE_ORG_MANAGER  先判断是否是组织管理员，是，就只能看，不能操作。不是的话，判断是否是维保人员

        if (alias.contains(RoleConstant.ROLE_REPAIR_MANAGER) || alias.contains(RoleConstant.ROLE_REPAIR)){

            ll_main_content.setVisibility(View.GONE);
            rl_weibao_content.setVisibility(View.VISIBLE);
            setRepairAction();
        }else {
            ll_main_content.setVisibility(View.VISIBLE);
            rl_weibao_content.setVisibility(View.GONE);
            // 初始化选中首页
            showFragment(0);
        }

//        //获取注册id
//        MobPush.getRegistrationId(new MobPushCallback<String>() {
//            @Override
//            public void onCallback(String data) {
//                System.out.println(Thread.currentThread().getId() + " RegistrationId:" + data);
//            }
//        });
    }

    private void initView() {
        ll_main_content = findViewById(R.id.ll_main_content);
        initHeadView();
        initBottomMenuBtn();

        rl_weibao_content = findViewById(R.id.rl_weibao_content);
        include_weibao_head_title = findViewById(R.id.include_weibao_head_title);
        include_weibao_head_title.setBackground(getResources().getDrawable(R.drawable.shape_head_title_bg_frame));
        TextView tv_title = include_weibao_head_title.findViewById(R.id.tv_title);
        tv_title.setText("预约维保单");
        tv_title.setTextColor(getResources().getColor(R.color.white));

        tv_choose_company = include_weibao_head_title.findViewById(R.id.tv_choose_company);
        tv_choose_company.setText(UserInfoModel.getCompandName(MainActivity.this));
        iv_setting = include_weibao_head_title.findViewById(R.id.iv_setting);

        iv_add_img = rl_weibao_content.findViewById(R.id.iv_add_img);
        iv_add_img.setVisibility(View.VISIBLE);
        iv_add_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 添加隐患整改
                setClickAction(ConstData.SHOWFRAG, ConstData.ADDYINGHUAN, "添加隐患整改单", null);
            }
        });

        baseFragment = new BarFloorFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ConstData.BARTYPE, "2");
        baseFragment.setArguments(bundle);
        addFragment(R.id.fl_weibao_container, baseFragment);
    }

    private void initHeadView() {
        include_head_title = findViewById(R.id.include_head_title);
        include_head_title.setBackground(getResources().getDrawable(R.drawable.shape_head_title_bg_frame));
        tv_title = findViewById(R.id.tv_title);
        tv_title.setTextColor(getResources().getColor(R.color.white));
        findViewById(R.id.v_divdier_line).setVisibility(View.GONE);
    }

    /**
     * 初始化底部按钮
     */
    private void initBottomMenuBtn() {
        ll_home = findViewById(R.id.ll_home);
        ll_home.setOnClickListener(this);
        iv_home = findViewById(R.id.iv_home);
        tv_home = findViewById(R.id.tv_home);

        ll_message = findViewById(R.id.ll_message);
        ll_message.setOnClickListener(this);
        iv_message = findViewById(R.id.iv_message);
        tv_message = findViewById(R.id.tv_message);

        ll_knowledge = findViewById(R.id.ll_knowledge);
        ll_knowledge.setOnClickListener(this);
        iv_knowledge = findViewById(R.id.iv_knowledge);
        tv_knowledge = findViewById(R.id.tv_knowledge);

        ll_my = findViewById(R.id.ll_my);
        ll_my.setOnClickListener(this);
        iv_my = findViewById(R.id.iv_my);
        tv_my = findViewById(R.id.tv_my);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ll_home:
                showFragment(0);
                break;
            case R.id.ll_message:
                showFragment(1);
                break;
            case R.id.ll_knowledge:
                showFragment(2);
                break;
            case R.id.ll_my:
                showFragment(3);
                break;
        }
    }

    /**
     * 显示fragment
     * @param pageType
     */
    private void showFragment(int pageType){
        if (pageType == currentSelectPosition){
            baseFragments[pageType].skipToTop();
            return;
        }
        setHeadType(pageType);
        changeBottomMenuBtnStatus(pageType);
        currentSelectPosition = pageType;
        BaseFragment baseFragment = baseFragments[pageType];
        if (null == baseFragment){
            switch (pageType){
                case 0:
                    baseFragment = initHomeFragment();
                    break;
                case 1:
                    baseFragment = initMessageFragment();
                    break;
                case 2:
                    baseFragment = initStatisticFragment();
                    break;
                case 3:
                    baseFragment = initUserCenterFragment();
                    break;
                default:
                    // baseFragment = initWebFragment();
                    break;
            }
            baseFragments[pageType] = baseFragment;
        }
        addFragment(R.id.fl_main, baseFragment);
    }

    private void setHeadType(int pageType) {
        switch (pageType){
            case 0:
                include_head_title.setVisibility(View.VISIBLE);
                tv_title.setText(tv_home.getText());
                break;
            case 1:
                include_head_title.setVisibility(View.VISIBLE);
                tv_title.setText(tv_message.getText());
                break;
            case 2:
                include_head_title.setVisibility(View.VISIBLE);
                tv_title.setText(tv_knowledge.getText());
                break;
            case 3:
                include_head_title.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 改变底部按钮状态
     * @param pageType
     */
    private void changeBottomMenuBtnStatus(int pageType) {
        switch (pageType){
            case 0:
                iv_home.setImageResource(R.drawable.icon_tab_home_checked);
                tv_home.setTextColor(this.getResources().getColor(R.color.main_color));
                iv_knowledge.setImageResource(R.drawable.icon_tab_knowledge_day);
                iv_message.setImageResource(R.drawable.icon_tab_order_day);
                tv_message.setTextColor(this.getResources().getColor(R.color.home_bottom_text_color));
                tv_knowledge.setTextColor(this.getResources().getColor(R.color.home_bottom_text_color));
                iv_my.setImageResource(R.drawable.icon_tab_usercenter_day);
                tv_my.setTextColor(this.getResources().getColor(R.color.home_bottom_text_color));
                break;
            case 1:
                iv_home.setImageResource(R.drawable.icon_tab_home_day);
                tv_home.setTextColor(this.getResources().getColor(R.color.home_bottom_text_color));
                iv_message.setImageResource(R.drawable.icon_tab_order_checked);
                tv_message.setTextColor(this.getResources().getColor(R.color.main_color));
                iv_knowledge.setImageResource(R.drawable.icon_tab_knowledge_day);
                tv_knowledge.setTextColor(this.getResources().getColor(R.color.home_bottom_text_color));
                iv_my.setImageResource(R.drawable.icon_tab_usercenter_day);
                tv_my.setTextColor(this.getResources().getColor(R.color.home_bottom_text_color));
                break;
            case 2:
                iv_home.setImageResource(R.drawable.icon_tab_home_day);
                tv_home.setTextColor(this.getResources().getColor(R.color.home_bottom_text_color));
                iv_knowledge.setImageResource(R.drawable.icon_tab_knowledge_checked);
                tv_message.setTextColor(this.getResources().getColor(R.color.home_bottom_text_color));
                iv_message.setImageResource(R.drawable.icon_tab_order_day);
                tv_knowledge.setTextColor(this.getResources().getColor(R.color.main_color));
                iv_my.setImageResource(R.drawable.icon_tab_usercenter_day);
                tv_my.setTextColor(this.getResources().getColor(R.color.home_bottom_text_color));
                break;
            case 3:
                iv_home.setImageResource(R.drawable.icon_tab_home_day);
                tv_home.setTextColor(this.getResources().getColor(R.color.home_bottom_text_color));
                iv_knowledge.setImageResource(R.drawable.icon_tab_knowledge_day);
                tv_message.setTextColor(this.getResources().getColor(R.color.home_bottom_text_color));
                iv_message.setImageResource(R.drawable.icon_tab_order_day);
                tv_knowledge.setTextColor(this.getResources().getColor(R.color.home_bottom_text_color));
                iv_my.setImageResource(R.drawable.icon_tab_usercenter_checked);
                tv_my.setTextColor(this.getResources().getColor(R.color.main_color));
                break;
        }
    }

    /**
     * 初始化首页
     */
    private BaseFragment initHomeFragment() {
        BaseFragment baseFragment = new HomeFragment();
        Bundle bundle = new Bundle();
        baseFragment.setArguments(bundle);
        return baseFragment;
    }

    /**
     * 初始化数据
     */
    private BaseFragment initMessageFragment() {
        BaseFragment baseFragment = new HomeMessageFragment();
        Bundle bundle = new Bundle();
        baseFragment.setArguments(bundle);
        return baseFragment;
    }

    /**
     * 初始化数据
     */
    private BaseFragment initStatisticFragment() {
        BaseFragment baseFragment = new HomeStatisticFragment();
        Bundle bundle = new Bundle();
        baseFragment.setArguments(bundle);
        return baseFragment;
    }

    /**
     * 初始化个人中心
     */
    private BaseFragment initUserCenterFragment() {
        BaseFragment baseFragment = new UserCenterFragment();
        return baseFragment;
    }

    /**
     * 初始化首页网页
     */
    private BaseFragment initWebFragment(String url, String title) {
        BaseFragment baseFragment = new WebFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ConstData.URL, url);
        if (!StringUtils.isEmpty(title)) {
            bundle.putString("title", title);
        }
        baseFragment.setArguments(bundle);
        return baseFragment;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (((Build.VERSION.SDK_INT < 5) && (keyCode == KeyEvent.KEYCODE_BACK))
                && (event.getRepeatCount() == 0)) {
            onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 点击两次返回退出系统
     * 该方法只适用android2.0及以上
     */
    @Override
    public void onBackPressed() {
        if (back_pressed + 3000 > System.currentTimeMillis()) {
            super.onBackPressed();
        } else {
            ToastUtils.showToast(this, getString(R.string.press_again_exit));
        }

        back_pressed = System.currentTimeMillis();
    }

    private void initUpdateHttpHelper(){
        try {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("version", "V" + Utils.getVersionName(this));
            hashMap.put("terminal", "App");
            HashMap<String, String> url_params = new HashMap<>();
            url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
            InfoListListHttpHelper infoListListHttpHelper = new InfoListListHttpHelper(this,
                    Url.APP_UPDATE_URL, APP_UPDATE_WHAT, handler, true, url_params);
            infoListListHttpHelper.setParseJsonData(new InfoListParseJsonData());
            infoListListHttpHelper.getHttpRequest(true);
        }catch (Exception e){}
    }


    private class InfoListListHttpHelper extends HttpHelper{

        public InfoListListHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }
    }

    protected class InfoListParseJsonData extends ParseJsonData {

        public InfoListParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {
            try {
                switch (what) {
                    case APP_UPDATE_WHAT:
                        JSONObject jsonObject = new JSONObject(dataStr);
                        AppVersionModel appVersionModel = JSONUtil.jsonObjectToBean(new JSONObject(jsonObject.getString("appVersion")), AppVersionModel.class);
                        bundle.putSerializable("data", appVersionModel);
                        bundle.putString("upgrade", jsonObject.getString("upgrade"));
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                    case GET_COMPANY_WHAT:
                        LinkedList<CompanyModel> companyModels = (LinkedList<CompanyModel>) JSONUtil.jsonArrayToBeanList(new JSONArray(dataStr), CompanyModel.class);
                        bundle.putSerializable("companyList", companyModels);
                        bundle.putBoolean(REQUEST_OK, true);
                        break;
                }
            }catch (Exception e){

            }
        }
    }

    @Override
    protected void dealWithMyMsgs(Message msg) {
        super.dealWithMyMsgs(msg);
        Bundle bundle = msg.getData();
        if (!bundle.getBoolean(ParseJsonData.REQUEST_OK) ||
                !ParseJsonData.REQUEST_OK_CODE.equals(bundle.getString(ParseJsonData.ERROR_CODE))){

            return;
        }
        switch (msg.what){
            case APP_UPDATE_WHAT:
                String upgrade = bundle.getString("upgrade");
                if ("true".equals(upgrade)) {
                    AppVersionModel appVersionModel = (AppVersionModel) bundle.getSerializable("data");
                    updateDialog = DialogUtils.createAppUpdateDialog(this, appVersionModel);
                    if ("1".equals(appVersionModel.getForceUpdate()) || !SimpleCache.isContainValueForOneDay(this, ConstData.UPDATE_DIALOG_SHOW, "1")) {
                        DialogUtils.showDialog(updateDialog);
                    }
                }
                break;
            case GET_COMPANY_WHAT:
                LinkedList<CompanyModel> list = (LinkedList<CompanyModel>) bundle.getSerializable("companyList");
                if (null != list && list.size() > 0){
                    // 切换公司
                    DialogUtils.closeDialog(changeCompanyDialog);
                    changeCompanyDialog = DialogUtils.createChangeCompanyDialog(MainActivity.this, list);
                    DialogUtils.showDialog(changeCompanyDialog);
                    changeCompanyDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                            tv_choose_company.setText(UserInfoModel.getCompandName(MainActivity.this));
                            if (null != baseFragment) {
                                baseFragment.updateData();
                            }
                        }
                    });
                }
                break;

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 删除图片临时文件
        Utils.clearPhotoData(this);
        if (null == updateDialog || !updateDialog.isShowing()) {
            initUpdateHttpHelper();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DialogUtils.closeDialog(updateDialog);
    }

    public void setRepairAction(){
        tv_choose_company.setVisibility(View.VISIBLE);
        iv_setting.setVisibility(View.VISIBLE);
        iv_add_img.setVisibility(View.GONE);
        tv_choose_company.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initGetCompanyHttpHelper();
            }
        });

        iv_setting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BannerModel bannerModel = new BannerModel();
                bannerModel.setActionTitle("设置");
                bannerModel.setActionType(ConstData.SHOWFRAG);
                bannerModel.setActionValue(ConstData.SETTING);
                MainActivity.this.setClickAction(bannerModel);
            }
        });
    }

    /**
     * 获取公司树
     */
    private void initGetCompanyHttpHelper(){
        HashMap<String, String> url_params = new HashMap<>();
        InfoListListHttpHelper getCompanyHttpHelper = new InfoListListHttpHelper(this, Url.QUERY_COMPANY_TREE, GET_COMPANY_WHAT, handler, true, url_params);
        getCompanyHttpHelper.setParseJsonData(new InfoListParseJsonData());
        getCompanyHttpHelper.getHttpRequest();
    }

}
